package orchestration.android.execution.tasks;

import orchestration.android.RunExecutionActivity;
import orchestration.android.execution.exceptions.TaskExecutionException;
import orchestration.persistence.exceptions.UnsupportedTypeException;
import android.content.Intent;
import android.content.pm.PackageManager;

/**
 * @author  <a href="mailto:car.ferrarini@gmail.com">Carlo Ferrarini</a>
 */
public class ActivityTask extends AndroidTask {

	/**
	 * @uml.property  name="intent"
	 */
	private Intent intent;
	/**
	 * @uml.property  name="ignoreBack"
	 */
	private boolean ignoreBack;
	/**
	 * @uml.property  name="result"
	 */
	private Intent result;
	
	public ActivityTask(String id) {
		super(id);
	}

	@Override
	public void onExecute(RunExecutionActivity atl) throws TaskExecutionException {
		if(atl.getPackageManager().queryIntentActivities(intent, PackageManager.GET_RESOLVED_FILTER).size()==0)
			throw new TaskExecutionException("Cannot find activities to handle the intent: action= " +intent.getAction() + " data= " + intent.getDataString());
		try {
			fillIntentExtras(atl,intent);
		} catch (UnsupportedTypeException e) {
			throw new TaskExecutionException(e);
		}
		int hashCode = getId().hashCode();
		if(hashCode<0)
			hashCode=0-hashCode;
		atl.startActivityForResult(intent, hashCode);
	}

	/**
	 * @param intent
	 * @uml.property  name="intent"
	 */
	public void setIntent(Intent intent) {
		this.intent = intent;
	}

	/**
	 * @return
	 * @uml.property  name="intent"
	 */
	public Intent getIntent() {
		return intent;
	}
	/**
	 * @return
	 * @uml.property  name="result"
	 */
	public Intent getResult() {
		return result;
	}

	/**
	 * @return
	 * @uml.property  name="ignoreBack"
	 */
	public boolean isIgnoreBack() {
		return ignoreBack;
	}

	/**
	 * @param ignoreBack
	 * @uml.property  name="ignoreBack"
	 */
	public void setIgnoreBack(boolean ignoreBack) {
		this.ignoreBack = ignoreBack;
	}



	/**
	 * @param result
	 * @uml.property  name="result"
	 */
	public void setResult(Intent result) {
		this.result = result;
	}

	/**
	 * 
	 * @param eia
	 * @param data
	 * @throws TaskExecutionException 
	 */
	public void manageResult(RunExecutionActivity eia) throws TaskExecutionException {
		Intent result=this.result;
		try {
			saveTaskOutput(eia, result);
		} catch (UnsupportedTypeException e) {
			throw new TaskExecutionException(e);
		}
	}
}
